package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import entity.Book;
import entity.Order;
import entity.OrderItem;
import util.DbUtil;

public class OrderItemDao {

	public void addOrderItems(List<OrderItem> orderItems) throws SQLException {
		// 生成订单条目
		QueryRunner runner = new QueryRunner();
		Connection conn = DbUtil.getConn();
		String sql = "insert into orderitem (order_id,book_id,buynum) values(?,?,?)";
		//批量插入
		for (OrderItem item:orderItems) {
			String order_id=item.getOrder().getId();
			String b_id=item.getP().getId();
			int num=item.getBuynum();
			runner.update(conn,sql,order_id,b_id,num);
		}
		
	}
	// 根据订单查找订单项.并将订单项中商品查找到。
		public List<OrderItem> findOrderItemByOrder(final Order order)
				throws SQLException {
			String sql = "select * from orderItem,book where book.id=orderItem.book_id and order_id=?";
			QueryRunner runner = new QueryRunner();
			Connection conn = DbUtil.getConn();
			return runner.query(conn,sql, new ResultSetHandler<List<OrderItem>>() {
				public List<OrderItem> handle(ResultSet rs) throws SQLException {

					List<OrderItem> items = new ArrayList<OrderItem>();
					while (rs.next()) {
						OrderItem item = new OrderItem();
						item.setOrder(order);
						item.setBuynum(rs.getInt("buynum"));
						Book p = new Book();
						p.setCategory(rs.getString("category"));
						p.setId(rs.getString("id"));
						p.setDescription(rs.getString("description"));
						p.setImgurl(rs.getString("imgurl"));
						p.setName(rs.getString("name"));
						p.setPnum(rs.getInt("pnum"));
						p.setPrice(rs.getDouble("price"));
						item.setP(p);
						items.add(item);
					}
					return items;
				}
			}, order.getId());
		}
		/*
		 * 根据id删除订单
		 */
		public void delOrderItems(String id) throws SQLException {
			// TODO Auto-generated method stub
			String sql="delete from orderItem where order_id=?";		
			QueryRunner runner = new QueryRunner();
			Connection conn = DbUtil.getConn();	
			runner.update(conn,sql,id);
		}
		


}
